package com.chinawlx.wlxteacher.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.WLXRxBus;
import com.chinawlx.wlxteacher.network.bean.WLXTimeLineBean;
import com.chinawlx.wlxteacher.network.bean.WLXUploadImagesBean;
import com.chinawlx.wlxteacher.network.bean.WLXUploadVideoBean;
import com.chinawlx.wlxteacher.ui.adapter.WLXTimeLineListViewAdapter;
import com.chinawlx.wlxteacher.ui.event.SendImagesEvent;
import com.chinawlx.wlxteacher.ui.event.SendVideoEvent;
import com.chinawlx.wlxteacher.ui.fragment.WLXLoadingFragment;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXFileUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXImageUtils;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXNetUtil;
import com.chinawlx.wlxteacher.utils.WLXSaveSQLiteUtil;
import com.chinawlx.wlxteacher.utils.WLXTeacherConstant;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_file;
import com.chinawlx.wlxteacher.wlx_fileDao;
import com.chinawlx.wlxteacher.wlx_grade_timeline;
import com.chinawlx.wlxteacher.wlx_grade_timelineDao;
import com.chinawlx.wlxteacher.wlx_statistics_student_class;
import com.chinawlx.wlxteacher.wlx_statistics_student_classDao;
import com.chinawlx.wlxteacher.wlx_student;
import com.chinawlx.wlxteacher.wlx_studentDao;
import com.chinawlx.wlxteacher.wlx_student_order_detail;
import com.chinawlx.wlxteacher.wlx_student_order_detailDao;
import com.chinawlx.wlxteacher.wlx_user;
import com.chinawlx.wlxteacher.wlx_userDao;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGAMeiTuanRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.functions.Action1;

/**
 * 学生详情界面
 * <p/>
 * Created by wlx on 16/9/18.
 */
public class WLXStudentDetailActivity extends WLXBaseActivity implements BGARefreshLayout
        .BGARefreshLayoutDelegate {
    @BindView(R.id.el_timeLine)
    ExpandableListView mElTimeLine;
    @BindView(R.id.fab_handHomework)
    FloatingActionButton mFabHandHomework;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.iv_call)
    ImageView mIvCall;
    @BindView(R.id.civ_head)
    CircleImageView mCivHead;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_studentId)
    TextView mTvStudentId;
    @BindView(R.id.tv_classNum)
    TextView mTvClassNum;
    @BindView(R.id.tv_homewordNum)
    TextView mTvHomewordNum;
    @BindView(R.id.tv_attendanceRatio)
    TextView mTvAttendanceRatio;

    private Context mContext;
    private String mGradeId;
    private String mStudentId;
    private Map<Long, ArrayList<wlx_grade_timeline>> mTimeLinehashMap = new HashMap<>();
    private List<Long> mDateList = new ArrayList<>();//时间戳集合

    private int mImageIndex = 0;//正在上传图片的索引
    private String mFamilyUserId = "";

    public static final String LOADING_TAG = "WLXCommentListActivity";

    private boolean mHasMoreData = true;//是否还有上拉数据

    private int paging_index = 1;//分页索引（1:表示第一页）
    private int paging_size = 10;

    private WLXLoadingFragment mLoadingFragment;
    private WLXTimeLineListViewAdapter mTimeLineListViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_detail);
        mContext = this;
        mLoadingFragment = WLXLoadingFragment.getInstance();
        mLoadingFragment.show(getSupportFragmentManager(), LOADING_TAG);
        final ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id
                .el_timeLine);
        expandableListView.addHeaderView(View.inflate(mContext, R.layout
                .student_detail_header_view, null));

        ButterKnife.bind(this);

        mGradeId = getIntent().getStringExtra(WLXTeacherConstant.GRADE_ID);
        WLXConstant.grade_id = mGradeId;

        mStudentId = getIntent().getStringExtra(WLXTeacherConstant.STUDENT_ID);
        WLXConstant.student_id = mStudentId;

        WLXLogUtil.printI("班级Id:" + mGradeId + "-----------学生id:" + mStudentId);

        //显示学生信息
        showStudentInfo();

        //获取时间线数据
        initTimeLineData();

        initRefreshLayout();

        WLXRxBus.getInstance().toObserverable().subscribe(new Action1<Object>() {
            @Override
            public void call(Object event) {
                if (event instanceof SendVideoEvent) {
                    sendVideo();
                }
                if (event instanceof SendImagesEvent) {
                    if (WLXConstant.IMAGES_PATH != null && WLXConstant.IMAGES_PATH.size() > 0) {
                        //上传第一张
                        mImageIndex = 0;

                        WLXLogUtil.printE("图片数量：" + WLXConstant.IMAGES_PATH.size());
                        sendImages(WLXConstant.IMAGES_PATH.get(mImageIndex));
                    }
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        });
    }

    /**
     * 上传视频文件
     */
    private void sendVideo() {
        WLXCustomToast.showTopToast("正在上传视频");
        File file = new File(WLXConstant.VIDEO_PATH);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        CountingRequestBody countingRequestBody = new CountingRequestBody(requestFile, new
//                CountingRequestBody.Listener() {
//            @Override
//            public void onRequestProgress(long bytesWritten, long contentLength) {
//                // TODO: 16/8/31 展示进度
//                final int percentage = (int) (bytesWritten / contentLength * 100);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        WLXCustomToast.getToast().cancel();
//                        WLXCustomToast.showTopToast("正在上传:" + percentage + "%");
//                    }
//                });
//            }
//        });
//        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(),
//                countingRequestBody);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(),
                requestFile);
        WLXHttpRxHelper.getInstance().uploadVideo(WLXConstant.RESOURCE_ID, "homework",
                WLXConstant.VIDEO_DURATION, body, new Subscriber<WLXUploadVideoBean>() {

            @Override
            public void onCompleted() {
                //文件发送完到服务器,就删除,之后删除数据库对应的记录
                File videoAppend = new File(WLXConstant.VIDEO_PATH);
                if (videoAppend.exists()) {
                    videoAppend.delete();
                }
                List<wlx_file> fileList = WLXGreenDaoUtil.getFileDao().queryBuilder().where
                        (wlx_fileDao.Properties.Resource_id.eq(WLXConstant.RESOURCE_ID)).list();
                if (fileList.size() > 0) {
                    wlx_file wlxFile = fileList.get(0);
                    WLXGreenDaoUtil.getFileDao().delete(wlxFile);
                }
                initTimeLineData();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(WLXUploadVideoBean uploadVideoBean) {
                if (uploadVideoBean.getCode() == 0) {
                    WLXCustomToast.showTopToast("上传成功");
                } else {
                    WLXCustomToast.show(uploadVideoBean.getMsg());
                }
            }
        });
    }

    /**
     * 上传图片文件
     */
    private void sendImages(final String imagePath) {
        WLXLogUtil.printE("上传的图片的路径："+imagePath);

        Map<String, RequestBody> params = new LinkedHashMap<>();
        File file;

        final double size = WLXFileUtil.getFileOrFilesSize(imagePath, WLXFileUtil.SIZETYPE_KB);
        if (size > 500) {
            //如果图片大小大于500K,就处理图片大小(系统相机拍的大图)
            file = new File(WLXImageUtils.zoomBitmap2File(imagePath));
        } else {
            file = new File(imagePath);
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        //file代表服务器接收到的key,file1.getName()代表文件名
        params.put("file\";filename=\"" + file.getName(), requestBody);

        params.put("resource_id", RequestBody.create(MediaType.parse("multipart/form-data"),
                WLXConstant.RESOURCE_ID));
        params.put("resource_code", RequestBody.create(MediaType.parse("multipart/form-data"),
                "homework"));

        WLXHttpRxHelper.getInstance().uploadImages(params, new Subscriber<WLXUploadImagesBean>() {

            @Override
            public void onStart() {
                super.onStart();
                WLXCustomToast.showTopToast("正在上传第" + (mImageIndex + 1) + "张图片");
            }

            @Override
            public void onCompleted() {
                //=======================上传之后图片不能删除(有可能是相册图片,不是app拍的)

                //最后一张上传成功之后,刷新界面
                if (mImageIndex == WLXConstant.IMAGES_PATH.size() - 1) {
                    List<wlx_file> fileList = WLXGreenDaoUtil.getFileDao().queryBuilder().where
                            (wlx_fileDao.Properties.Resource_id.eq(WLXConstant.RESOURCE_ID)).list();
                    if (fileList.size() > 0) {
                        wlx_file wlxFile = fileList.get(0);
                        WLXGreenDaoUtil.getFileDao().delete(wlxFile);
                    }
                    WLXCustomToast.showTopToast("所有图片上传完成");
                    initTimeLineData();
                }

                //=============================前一张图片上传成功之后继续传下一张
                if (mImageIndex < WLXConstant.IMAGES_PATH.size() - 1) {
                    mImageIndex++;
                    sendImages(WLXConstant.IMAGES_PATH.get(mImageIndex));
                }
            }

            @Override
            public void onError(Throwable e) {
                WLXCustomToast.showTopToast("上传图片出现错误");
            }

            @Override
            public void onNext(WLXUploadImagesBean uploadImagesBean) {
                if (uploadImagesBean.getCode() == 0) {
                    WLXLogUtil.printE("第" + mImageIndex + "上传成功");
                    WLXCustomToast.showTopToast("第" + (mImageIndex + 1) + "上传成功");

                    //===========自己拍的图片上传成功之后,自动删除,并通知图库更新删除缩略图=============
                    if (imagePath.contains(WLXConstant.ExternalCacheDir)) {
                        getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                MediaStore.Images.Media.DATA + "=?", new String[]{imagePath});
                    }
                } else {
                    WLXCustomToast.show(uploadImagesBean.getMsg());
                }
            }
        });

    }


    /**
     * 读数据库显示学生信息
     */
    @SuppressLint("SetTextI18n")
    private void showStudentInfo() {
        //读数据库显示学生信息
        mTvStudentId.setText("学号: " + mStudentId);

        final List<wlx_student> studentList = WLXGreenDaoUtil.getStudentDao().queryBuilder()
                .where(wlx_studentDao.Properties.Student_id.eq(mStudentId)).list();
        if (studentList.size() > 0) {
            final wlx_student student = studentList.get(0);
            mTvName.setText(student.getRealname());

            Glide.with(mContext).load(student.getAvatar_url()).dontAnimate().placeholder(R
                    .drawable.place_holder).into(mCivHead);

            mFamilyUserId = student.getFamily_user_id() + "";

            // 拿着student_id去order表查,显示课次情况
            final List<wlx_student_order_detail> orderDetails = WLXGreenDaoUtil
                    .getStudentOrderDetailDao().queryBuilder().where(wlx_student_order_detailDao
                            .Properties.Student_id.eq(mStudentId)).list();
            if (orderDetails.size() > 0) {
                final wlx_student_order_detail orderDetail = orderDetails.get(0);

                //作业次数,课次情况
                mTvHomewordNum.setText(orderDetail.getHomework_count() + "");
                mTvClassNum.setText(orderDetail.getConsume_number() + "/" + orderDetail
                        .getTotal_number());

                //月出勤课次比
                final int year = Calendar.getInstance().get(Calendar.YEAR);
                final int month = Calendar.getInstance().get(Calendar.MONTH);
                WLXLogUtil.printE("年:" + year + "月:" + month);

                final List<wlx_statistics_student_class> statisticsStudentClasses =
                        WLXGreenDaoUtil.getStatisticsStudentDao().queryBuilder().where
                                (wlx_statistics_student_classDao.Properties.Student_id.eq
                                        (mStudentId), wlx_statistics_student_classDao.Properties
                                        .Year.eq(year), wlx_statistics_student_classDao
                                        .Properties.Month.eq(month)).list();
                if (statisticsStudentClasses.size() > 0) {
                    final wlx_statistics_student_class studentClass = statisticsStudentClasses
                            .get(0);
                    mTvAttendanceRatio.setText((studentClass.getWork_count() - studentClass
                            .getUnwork_count()) + "/" + studentClass.getWork_count());
                } else {
                    mTvAttendanceRatio.setText("0/0");
                }
            }

        }

    }

    /**
     * 获取时间线数据
     */
    private void initTimeLineData() {
        WLXHttpRxHelper.getInstance().timeLine(mStudentId, mGradeId, paging_index, paging_size,
                new Subscriber<WLXTimeLineBean>() {

            @Override
            public void onCompleted() {
                showTimeLine();
            }

            @Override
            public void onError(Throwable e) {
                onCompleted();
            }

            @Override
            public void onNext(WLXTimeLineBean timeLine) {
                if (timeLine.getCode() == 0) {
                    if (timeLine.getData() != null) {
                        WLXTimeLineBean.Data data = timeLine.getData();
                        if (data != null) {
                            if (data.getFamily_user() != null) {
                                //==================存储wlx_schedule=================
                                WLXSaveSQLiteUtil.saveWlxUser(data.getFamily_user());
                            }

                            if (data.getTimeline_list() != null && data.getTimeline_list().size()
                                    > 0) {
                                //==================存储wlx_grade_timeline=================
                                WLXSaveSQLiteUtil.saveWlxGradeTimeline(data.getTimeline_list());
                            }
                        }
                    }
                } else {
                    WLXCustomToast.show(timeLine.getMsg());
                }
            }
        });
    }

    /**
     * 读数据库,展示时间线
     */
    private void showTimeLine() {
        mLoadingFragment.dismiss();

        List<wlx_grade_timeline> timelineList = WLXGreenDaoUtil.getGradeTimeLineDao()
                .queryBuilder().where(wlx_grade_timelineDao.Properties.Student_id.eq(mStudentId),
                        wlx_grade_timelineDao.Properties.Grade_id.eq(mGradeId)).orderDesc
                        (wlx_grade_timelineDao.Properties.Creation_date).offset((paging_index -
                        1) * paging_size).limit(paging_size).list();
        if (paging_index == 1) {
            //这是下拉刷新
            mTimeLinehashMap.clear();
            mDateList.clear();
            mRefreshLayout.endRefreshing();
            if (timelineList.size() > 0) {
                mElTimeLine.setVisibility(View.VISIBLE);
                Long key;
                for (wlx_grade_timeline timeline : timelineList) {
                    //==============按照creation_date按天分组
                    key = timeline.getCreation_date() / (60 * 60 * 24);
                    if (!mTimeLinehashMap.containsKey(key)) {
                        mTimeLinehashMap.put(key, new ArrayList<wlx_grade_timeline>());
                        mDateList.add(key);
                    }
                    mTimeLinehashMap.get(key).add(timeline);
                }

                //===============================注意:因为ExpandListView更新数据时的特性,
                // 目前采用new一个Adapter的方式解决bug
                mTimeLineListViewAdapter = new WLXTimeLineListViewAdapter(mContext, mDateList,
                        mTimeLinehashMap);
                mElTimeLine.setAdapter(mTimeLineListViewAdapter);

                //设置点击不回缩
                mElTimeLine.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                    @Override
                    public boolean onGroupClick(ExpandableListView expandableListView, View view,
                                                int groupPosition, long id) {
                        return true;
                    }
                });
                // 设置默认展开
                for (int i = 0; i < mDateList.size(); i++) {
                    mElTimeLine.expandGroup(i);
                }
            } else {
                mElTimeLine.setVisibility(View.GONE);
            }
        } else {
            //上拉加载更多
            mRefreshLayout.endLoadingMore();
            if (timelineList.size() > 0) {
                Long key;
                for (wlx_grade_timeline timeline : timelineList) {
                    //==============按照creation_date按天分组
                    key = timeline.getCreation_date() / (60 * 60 * 24);
                    if (!mTimeLinehashMap.containsKey(key)) {
                        mTimeLinehashMap.put(key, new ArrayList<wlx_grade_timeline>());
                        mDateList.add(key);
                    }
                    if (!mTimeLinehashMap.get(key).contains(timeline)) {
                        mTimeLinehashMap.get(key).add(timeline);
                    }
                }
                mTimeLineListViewAdapter.notifyDataSetChanged();

                for (int i = 0; i < mTimeLineListViewAdapter.getGroupCount(); i++) {
                    //==========Group 的伸缩会引起getChildView,刷新childView=======
                    mElTimeLine.collapseGroup(i);
                    mElTimeLine.expandGroup(i);
                }
                if (timelineList.size() < paging_size) {
                    mHasMoreData = false;//没有更多数据了
                    WLXCustomToast.show("已经是最后一页了");
                }
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.iv_call, R.id.ll_attendanceRatio, R.id.fab_handHomework})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_call:
                //=================打家长电话
                final List<wlx_user> userList = WLXGreenDaoUtil.getUserDao().queryBuilder().where
                        (wlx_userDao.Properties.User_id.eq(mFamilyUserId)).list();
                if (userList.size() > 0) {
                    final String mobile = userList.get(0).getMobile();
                    //ACTION_CALL:直接拨号,ACTION_DIAL:拨号界面
                    startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mobile)));
                } else {
                    WLXCustomToast.show("未找到家长的联系方式");
                }
                break;
            case R.id.ll_attendanceRatio:
                //出勤率
                startActivity(new Intent(mContext, WLXAttendanceRatioActivity.class));
                break;
            case R.id.fab_handHomework:
                //提交月成果(视频或者图片)
                startActivity(new Intent(mContext, WLXRecordVideoPhotoActivity.class));
                break;
        }
    }

    //--------刷新内容    start---------
    private BGARefreshLayout mRefreshLayout;


    private void initRefreshLayout() {
        mRefreshLayout = (BGARefreshLayout) findViewById(R.id.rl_modulename_refresh);
        mRefreshLayout.setDelegate(this);
        BGAMeiTuanRefreshViewHolder meiTuanRefreshViewHolder = new BGAMeiTuanRefreshViewHolder
                (this, true);
        meiTuanRefreshViewHolder.setPullDownImageResource(R.drawable.yuanq);
        meiTuanRefreshViewHolder.setChangeToReleaseRefreshAnimResId(R.drawable
                .bga_refresh_mt_change_to_release_refresh);
        meiTuanRefreshViewHolder.setRefreshingAnimResId(R.drawable.bga_refresh_mt_refreshing);

        mRefreshLayout.setRefreshViewHolder(meiTuanRefreshViewHolder);
    }

    //开始刷新
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.netIsAvailable()) {
            paging_index = 1;
            mHasMoreData = true;//下拉刷新，有更多数据
            mLoadingFragment.show(getSupportFragmentManager(), LOADING_TAG);
            initTimeLineData();
        } else {
            WLXCustomToast.show("网络不可用");
            mRefreshLayout.endRefreshing();
        }
    }

    //处理上拉加载,在这里上拉加载更多,
    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.netIsAvailable()) {
            if (mHasMoreData) {
                paging_index++;
                mLoadingFragment.show(getSupportFragmentManager(), LOADING_TAG);
                initTimeLineData();
                return true;
            } else {
                WLXCustomToast.show("没有更多数据");
                return false;
            }
        } else {
            WLXCustomToast.show("网络不可用");
            return false;
        }
    }
    //--------刷新内容    end---------

}
